import createVanilla from 'zustand/vanilla'
import { subscribeWithSelector } from 'zustand/middleware'
import create from 'zustand'
import { LiveEntity, LiveModel } from '@/api/manager/live/interface'
import { useParamsStore } from '../../store'
import { transLive } from '@/api/manager/live/translator'
import { isMatch } from '@/pages/manager/utils/utils'
import { liveListSort } from './utils'
import { interval, Subject } from 'rxjs'
import { map, mergeMap, startWith, take } from 'rxjs/operators'

type StateStore = {
	list: LiveModel[]
	isLive: boolean
}
type IStore = StateStore & {
	update: (d: Partial<StateStore>) => void
	reset: () => void
	tableItemCalling: (userCookie: string) => void
	ws: {
		live_conf_mt_add: (mt: LiveEntity) => void
		live_conf_mt_del: (mt: LiveEntity) => void
		live_conf: (live: 0 | 1) => void
	}
}
const initialState: StateStore = {
	list: [],
	isLive: false,
}
export const store = createVanilla<IStore>()(
	subscribeWithSelector((set, get) => {
		const tableItemCalling$ = new Subject()
		tableItemCalling$
			.pipe(
				mergeMap((userCookie) =>
					interval(2000).pipe(
						map(() => false),
						take(1),
						startWith(true),
						map((isCalling) => {
							let list = get().list
							let item = list.find((x) => x.live.userCookie === userCookie)
							if (item) {
								item.status.isCalling = isCalling
							}
							return list
						})
					)
				)
			)
			.subscribe((list) => {
				set({ list: [...list] })
			})
		return {
			...initialState,
			update: (d) => set({ ...d }),
			reset: () => set(initialState),
			tableItemCalling: (userCookie) => {
				tableItemCalling$.next(userCookie)
			},
			ws: {
				live_conf_mt_add: (l) => {
					let list = get().list
					const keywords = useParamsStore.getState().keywords
					let mt = transLive(l)
					mt.status.isMatchSearch = isMatch(mt.mcc, keywords)
					list = list.filter((x) => x.live.userCookie !== mt.live.userCookie)
					list.push(mt)
					list = liveListSort(list)
					set({ list })
				},
				live_conf: (live) => {
					set({ isLive: !!live })
				},
				live_conf_mt_del: (l) => {
					let list = get().list
					list = list.filter((x) => x.live.userCookie !== l.user_token)
					set({ list: [...list] })
				},
			},
		}
	})
)
export const useTableLiveStore = create(store)
